package io.gitee.hejiang;

import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SwaggerSqlAuthController {
	@Value("${spring.mvc.spa-base-path}")
    private String spaBasePath;
	
	@GetMapping(value = "/auth/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.logout();
		request.getSession().invalidate();
		
        String location = request.getServletContext().getContextPath();
    	location = location == null ? spaBasePath : (location + spaBasePath).replaceAll("//", "/");

    	response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", location);
	}

	@GetMapping(value = "/auth/currentUser", produces = "application/json;charset=utf-8")
	public Object currentUser(HttpServletRequest request) {
		Map<String, Object> ret = new HashMap<>();

		Principal p = request.getUserPrincipal();
		ret.put("name", p != null ? p.getName() : "Swagger-SQL");

		return ret;
	}
}
